<template>
  <div class="leave-container">
    <van-nav-bar title="请假" fixed placeholder left-arrow @click="handleBack" />
    <!-- 申请表单 -->
    <van-form class="form-card" @submit="handleSubmit">
      <van-cell-group inset>
        <!-- 请假类型 -->
        <van-field
          v-model="displayLeaveType" 
          name="leaveType"
          label="*请假类型"
          placeholder="请选择类型"
          is-link
          readonly
          required
          @click="showTypePicker = true"
        >
        </van-field>
        <!-- 开始时间 -->
        <van-field
          v-model="form.startTime"
          name="startTime"
          label="开始时间"
          placeholder="选择开始日期"
          is-link
          readonly
          required
          @click="showStartPicker = true"
        />
        
        <!-- 结束时间 -->
        <van-field
          v-model="form.endTime"
          name="endTime"
          label="结束时间"
          placeholder="选择结束日期"
          is-link
          readonly
          required
          @click="showEndPicker = true"
        />
        
        <!-- 自动计算时长 -->
        <van-field
          v-model="form.duration"
          name="duration"
          label="请假时长"
          readonly
        >
          <template #extra>
            <span class="duration-text">{{ form.duration || 0 }} 天</span>
          </template>
        </van-field>
        
        <!-- 事由输入 -->
        <van-field
          v-model="form.reason"
          name="reason"
          label="请假事由"
          type="textarea"
          placeholder="请输入详细事由..."
          rows="4"
          autosize
          required
        />
      </van-cell-group>

      <!-- 提交按钮 -->
      <div class="submit-btn">
        <van-button 
          round 
          block 
          type="primary" 
          native-type="submit"
          :loading="submitting"
        >
          提交申请
        </van-button>
      </div>
    </van-form>

    <!-- 历史记录 -->
    <div class="history-card">
      <van-list
        v-model:loading="loading"
        :finished="finished"
        finished-text="没有更多记录"
        @load="loadHistory"
      >
      
        <van-cell 
          v-for="(item, index) in historyList" 
          :key="index"
          :title="`${getLeaveTypeName(item.leaveType)} | ${item.duration}天 |  原因：${ item.reason }`"
          :value="item.timeRange"
        >
        <span class="create-time">{{ item.createTime }}</span>
        <template #label>
          <!-- <div class="reason-label">{{ item.reason }}</div> -->
          <div class="time-info">
              <span>开始时间：{{ item.startTime }}</span>
              <span>结束时间：{{ item.endTime }}</span>
            </div>
            <van-tag 
              :type="statusTagMap[item.status]" 
              size="medium"
              class="status-tag"
            >
              {{ statusTextMap[item.status] }}
                  <!-- 新增的备注信息 -->
            </van-tag>
            <span v-if="(item.status === 1 || item.status === 2) && item.approveComment" class="approve-comment">备注：{{ item.approveComment }}</span>
            <van-button class="cancelLeave" v-if="item.status === 0" type="danger" size="small" @click="cancelLeave(item.id)">撤销申请</van-button>
          </template>
        </van-cell>
      </van-list>
    </div>

    <!-- 类型选择器 -->
    <van-popup v-model:show="showTypePicker" position="bottom">
      <van-picker
        :columns="typeOptions"
        @confirm="onTypeConfirm"
        @cancel="showTypePicker = false"
      />
    </van-popup>

    <!-- 开始时间选择器 -->
    <van-popup v-model:show="showStartPicker" position="bottom">
      <van-date-picker
        :min-date="new Date()"
        @confirm="handleStartConfirm"
        @cancel="showStartPicker = false"
      />  
    </van-popup>

    <!-- 结束时间选择器 -->
    <van-popup v-model:show="showEndPicker" position="bottom">
      <van-date-picker
        :min-date="form.startTime ? new Date(form.startTime) : new Date()"
        @confirm="handleEndConfirm"
        @cancel="showEndPicker = false"
      />
    </van-popup>
  </div>
</template>

<script setup>
import { ref,computed} from 'vue'
import moment from 'moment'
import { showToast } from 'vant'
import { submitLeaveService ,getLeaveHistoryApi,cancelLeaveService} from '@/api/leave'
import { Toast } from 'vant'
import { 
  showNotify
} from 'vant'
// 表单数据
const form = ref({
  leaveType: 'null',
  startTime: '',
  endTime: '',
  duration: 0,
  reason: ''
})
import {useRouter} from 'vue-router'
const router = useRouter()
const handleBack = () => {
  // 这里根据实际情况实现返回逻辑，比如使用 Vue Router 进行页面跳转
  router.push('/workbenches')
  console.log('返回上一页')
} 
// 历史记录
const historyList = ref([])
const loading = ref(false)
//  分页控制  
const finished = ref(false)
const currentPage = ref(1)

// 状态映射
const statusTextMap = ['待审批', '已通过', '已拒绝','已撤销']
const statusTagMap = ['primary', 'success', 'danger', 'warning']
// 调整类型选项配置
const typeOptions = ref([
  { text: '病假', value: 0 },
  { text: '事假', value: 1 },
  { text: '年假', value: 2 },
  { text: '调休', value: 3 }
])

// 获取请假类型文字
const getLeaveTypeName = (type) => {
  const option = typeOptions.value.find(option => option.value === type)
  return option? option.text : '未知类型'
}
const displayLeaveType = computed({
  get: () => typeOptions.value.find(o => o.value === form.value.leaveType)?.text || '',
  set: () => {}
})

const onTypeConfirm = ({ selectedOptions }) => {
  form.value.leaveType = selectedOptions[0]?.value ?? ''
  showTypePicker.value = false
}

// 弹窗控制
const showTypePicker = ref(false)
const showStartPicker = ref(false)
const showEndPicker = ref(false)
const submitting = ref(false)

// 时间处理
// 开始时间处理
const handleStartConfirm = (date) => {
  const [year, month, day] = date.selectedValues
  const newStartDate = moment(`${year}-${month}-${day}`, "YYYY-MM-DD")
  
  // 如果新开始时间晚于现有结束时间，则清空结束时间
  if (form.value.endTime && newStartDate.isAfter(form.value.endTime)) {
    form.value.endTime = ''
    showToast('已清空无效的结束时间，请重新选择')
  }
  
  form.value.startTime = newStartDate.format('YYYY-MM-DD')
  showStartPicker.value = false
  calculateDuration()
}

const handleEndConfirm = (date) => {
  const [year, month, day] = date.selectedValues
  const newEndDate = moment(`${year}-${month}-${day}`, "YYYY-MM-DD")
  
  // 强制时间顺序校验
  if (form.value.startTime && newEndDate.isBefore(form.value.startTime)) {
    showToast('结束时间不能早于开始时间')
    return
  }
  
  form.value.endTime = newEndDate.format('YYYY-MM-DD')
  showEndPicker.value = false
  calculateDuration()
} 

// 自动计算时长
const calculateDuration = () => {
  if (form.value.startTime && form.value.endTime) {
    const start = moment(form.value.startTime);
    const end = moment(form.value.endTime);
    form.value.duration = end.diff(start, 'days') + 1;
  }
}




// 表单提交
const handleSubmit = async () => {
  console.log(form.value);
  const submitData = {
    ...form.value,
    startDate: moment(form.value.startTime).format('YYYY-MM-DD'), // 改为与DTO匹配的字段名
    endDate: moment(form.value.endTime).format('YYYY-MM-DD'),
    leaveType: Number(form.value.leaveType) // 确保类型转换
  }
  
  // 删除原字段避免混淆
  delete submitData.startTime
  delete submitData.endTime
  if (!validateForm()) return
  
  submitting.value = true
  
  const result = await submitLeaveService(submitData)
  showNotify({ type: 'success', message: result.description || '提交成功' });
  submitting.value = false
  loadHistory(true)
}

const loadHistory = async (reset = false) => {  
  if (reset) {
    currentPage.value = 1
    historyList.value = []
    finished.value = false
  }
  if (finished.value) return
  loading.value = true
  try {
    const res = await getLeaveHistoryApi(currentPage.value)
    if (res.data.records && res.data.records.length > 0) {
      const sortedRecords = res.data.records.slice().reverse()
      historyList.value = reset ? sortedRecords : [...sortedRecords, ...historyList.value]
      currentPage.value++
      finished.value = res.data.records.length < 5
    } else {
      finished.value = true
    }
  } catch (error) {
    console.error('加载历史记录出错:', error)
  } finally {
    loading.value = false
  }
}

// 表单验证
const validateForm = () => {
  if (form.value.leaveType === null || form.value.leaveType === undefined) {
    showToast('请选择请假类型')
    return false
  }
  if (!form.value.startTime) {
    showToast('请选择开始时间')
    return false
  }
  if (!form.value.endTime) {
    showToast('请选择结束时间')
    return false
  }
  if (moment(form.value.endTime).isBefore(form.value.startTime)) {
    showToast('结束时间不能早于开始时间')
    return false
  }
  if (!form.value.reason.trim()) {
    showToast('请填写事由')
    return false
  }
  return true
}
// 撤销请假
const cancelLeave = async (leaveId) => {
    const result = await cancelLeaveService(leaveId)
      showToast('撤销成功')
      loadHistory(true)
}
// 重置表单
const resetForm = () => {
  form.value = {
    leaveType: 'null',
    startTime: '',
    endTime: '',
    duration: 0,
    reason: ''
  }
}
</script>

<style scoped>
.leave-container {
  background: #f8f8f8;
  min-height: 100vh;
}

.form-card {
  margin: 16px;
  background: white;
  border-radius: 12px;
  overflow: hidden;
  box-shadow: 0 2px 8px rgba(0,0,0,0.05);
}

.submit-btn {
  padding: 20px 16px 16px;
}

.duration-text {
  color: #1989fa;
  font-weight: 500;
}

.reason-label {
  color: #666;
  font-size: 13px;
  margin: 8px 0;
  line-height: 1.5;
}

.status-tag {
  margin-top: 6px;
}

.history-card {
  margin: 16px;
  background: white;
  border-radius: 12px;
  overflow: hidden;
  box-shadow: 0 2px 8px rgba(0,0,0,0.05);
  
  :deep(.van-cell__value) {
    flex: none;
    width: 40%;
    text-align: right;
    color: #666;
  }
}

.van-picker__confirm {
  color: #1989fa;
}
.time-info span,
.status-info span,
.leave-off-info {
  display: block;
  margin-bottom: 4px;
}
.history-card :deep(.van-cell[status="3"]) {
  color: #999;
  background-color: #f2f2f2;
}
.cancelLeave {
    position: absolute;
    bottom: 16px;
    right: 16px;
    z-index: 10; /* 设置较高的层级 */
} 
.create-time {
  color: #999;
  font-size: 12px;
}
.status-tag .approve-comment {
  margin-left: 5px;
  color: #999;
  font-size: 12px;
}
</style>    